;
var helper = require("../../javascript/helper");
var db = require("../../javascript/mysql");
var request = require("request");

var mysql = new db.mysqlClient("accident")
var url = "https://www.ergo-life.cn//Admin/getCALCUData.do";
//生成产品数据
function genProdutInfo() {
    projects = [];
    plan = {
        "planA": {
            "year": ["0-80"],
            "days": ["1d", "2d", "4d", "9d", "15d"],
            "people_count": ["1"],
            "accident_death": ["100000"],
            "accident_medical": ["10000"]
        },
        "planB": {
            "year": ["0-80"],
            "days": ["1d", "2d", "4d", "9d", "15d"],
            "people_count": ["1"],
            "accident_death": ["200000"],
            "accident_medical": ["20000"]
        }

    }

    for (k in plan) {
        data = helper.product([plan[k]["year"], plan[k]["days"], plan[k]["people_count"], plan[k]["accident_death"], plan[k]["accident_medical"]])
        for (i = 0; i < data.length; i++) {
            dt = helper.formatProductInfo(data[i], plan[k]);
            projects.push(dt);

        }
    };
    return projects;


}
//执行爬虫
function httpRequest(dt) {
    if (dt.accident_death == "100000") {
        planCd = "nets0147"
    } else {
        planCd = "nets0148"
    }
    params = {
        "productNo": "18",
        "insuredSex": "",
        "insuredBirthday": "",
        "insuranceYears": dt.days.replace("d", ""),
        "paymentPeriod": "",
        "guaranteeAmount": "",
        "mult": "0",
        "payIntv": "0",
        "insuyearFlag": "D",
        "payendyearFlag": "",
        "contPlanCode": planCd,
    }
    
    return new Promise(function (resolve, reject) {
        request({
            url: url,
            method: "POST",
            json: false,
            rejectUnauthorized: false,
            headers: {
                "Accept": "application/json, text/javascript, */*; q=0.01",
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36"
            },
            body: helper.urlencode(params)
        }, function (err, res, body) {
            if (!err && res.statusCode == 200) {
                if (body.indexOf("result") != -1) {
                    price = Number(JSON.parse(body).result).toFixed(2).toString();
                    rs = {
                        "name": "境内自驾游保险",
                        "company": "德华安顾人寿",
                        "price": price
                    }
                    resolve(rs);
                }
            }

        })


    })

}
var main = async function () {
    var data = genProdutInfo();
    for(i=0;i<data.length;i++){
        dt = data[i]
        rs = await httpRequest(dt);
        result = Object.assign( dt,rs );
        mysql.insertData( result );
    }
    mysql.close();

}
main();
